package club.pinea.client;

import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.LobbyProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import static club.pinea.proto.CommandProto.Command.*;

/**
 * @author pineapple
 * @date 2017年12月26日 下午1:31:13
 * @description xxx
 */
public class TimeClientHandler extends SimpleChannelInboundHandler<BasicProto.BaseMessage> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        LobbyProto.RoomRequest roomRequest = LobbyProto.RoomRequest.newBuilder()
//                .setRoom(1)
//                .setUserId(100001)
//                .build();
//        BasicProto.BaseMessage baseMessage = BasicProto.BaseMessage.newBuilder()
//                .setOrder(C_S_ROOM_VALUE)
//                .setBody(roomRequest.toByteString())
//                .build();
//        System.out.println("进入房间");
        //更新大厅
        LobbyProto.LeaveSeatRequest request = LobbyProto.LeaveSeatRequest.newBuilder()
                .setUserId(1001)
                .setSeatNum(1)
                .build();
        BasicProto.BaseMessage baseMessage = BasicProto.BaseMessage.newBuilder()
                .setOrder(C_S_LEAVE_ROOM_VALUE)
                .setBody(request.toByteString())
                .build();
        System.out.println("更新大厅信息请求发送~");
        ctx.writeAndFlush(baseMessage);

    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, BasicProto.BaseMessage baseMessage) throws Exception {
//        System.out.println("我收到了服务器端发送的数据" + System.currentTimeMillis());
//        System.out.println("NOW is: " + baseMessage);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("出错了");
        ctx.close();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.WRITER_IDLE) {
                BasicProto.HeartRequest request = BasicProto.HeartRequest.newBuilder().build();
                BasicProto.BaseMessage baseMessage = BasicProto.BaseMessage.newBuilder()
                        .setOrder(CommandProto.Command.C_S_HEART_VALUE)
                        .setBody(request.toByteString())
                        .build();
                ctx.writeAndFlush(baseMessage);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
